package club.mrxiao.gps.common.config;

import club.mrxiao.gps.common.properties.ThreadProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 * @author xiaoyu
 */

@Slf4j
@Configuration
@EnableAsync
public class ExecutorConfig {

    private final ThreadProperties threadProperties;

    public ExecutorConfig(ThreadProperties threadProperties) {
        this.threadProperties = threadProperties;
    }


    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(5);
        taskScheduler.setThreadNamePrefix("system-task-");
        taskScheduler.initialize();
        return taskScheduler;
    }

    @Bean(name = "gpsExecutor")
    public Executor gpsExecutor() {
        log.info("start gpsExecutor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(this.threadProperties.getCorePoolSize());
        //配置最大线程数
        executor.setMaxPoolSize(this.threadProperties.getMaxPoolSize());
        //配置队列大小
        executor.setQueueCapacity(this.threadProperties.getQueueCapacity());
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix(this.threadProperties.getNamePrefix());
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }
}
